import scrapy
import requests
from bid.items import BidItem
from bid.tools import *


class YunanSpider(scrapy.Spider):
    name = 'yunnan'
    allowed_domains = ['ggzy.yn.gov.cn']
    start_urls = ['https://ggzy.yn.gov.cn/']
    t_lis = [
        ['http://ggzy.yn.gov.cn/jyxx/jsgcZbgg', '工程建设-招标公告','1'],
        ['http://ggzy.yn.gov.cn/jyxx/jsgcBgtz', '工程建设-更正事项','2'],
        ['http://ggzy.yn.gov.cn/jyxx/jsgcpbjggs', '工程建设-评标结果公示','2'],
        ['http://ggzy.yn.gov.cn/jyxx/jsgcZbjggs', '工程建设-中标公告','3'],
        ['http://ggzy.yn.gov.cn/jyxx/jsgchtgs', '工程建设-合同公示','3'],
        ['http://ggzy.yn.gov.cn/jyxx/jsgcZbyc', '工程建设-招标异常','2'],
        ['http://ggzy.yn.gov.cn/jyxx/zfcg/cggg', '政府采购-采购公告','1'],
        ['http://ggzy.yn.gov.cn/jyxx/zfcg/gzsx', '政府采购-更正事项','2'],
        ['http://ggzy.yn.gov.cn/jyxx/zfcg/zbjggs', '政府采购-中标结果','3'],
        ['http://ggzy.yn.gov.cn/jyxx/zfcg/htgs', '政府采购-合同公示','3'],
        ['http://ggzy.yn.gov.cn/jyxx/zfcg/zfcgYcgg', '政府采购-异常公告','2'],
    ]
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36'}
    msg = []
    def start_requests(self):
        for lis in self.t_lis:
            for page in range(1, 9999):
                res = requests.post(lis[0],data={'currentPage':str(page)}, headers=self.headers)
                res.encoding = 'utf-8'
                ls = re.findall('<td\s*>\s*<a href="(.*?)" target="_blank" title="(.*?)".*?<td>(\d{4}-\d{2}-\d{2})<', res.text, re.S)
                last_page = re.findall('class="dian">共(\d+)页', res.text, re.S)[0]
                if page > int(last_page):
                    break
                for l in ls:
                    item = {}
                    item['link'] = 'http://ggzy.yn.gov.cn' + l[0]
                    item['title'] = l[1]
                    item['time'] = l[2]
                    item['classification'] = '云南-'+lis[1]
                    item['typ'] = lis[-1]
                    if redis_dupefilter(item) or item['time'].startswith('2021'):
                        self.msg.append(lis)
                        break
                    yield scrapy.Request(url=item['link'], callback=self.parse, meta={'item': item})
                if lis in self.msg:
                    print(lis[1],'完成')
                    break
                time.sleep(len(ls))

    def parse(self, response):
        item = BidItem()
        item.update(response.meta['item'])
        item['content'] = get_content(response.text, '//div[@class="detail_contect"]|//div[@class="page_contect bai_bg"]')
        item = get_field(dict(item))
        yield item